//
//  UdpSingleton.m
//  Lead Show 3.0
//
//  Created by Maculish Ting on 14/10/31.
//  Copyright (c) 2014年 Leyard Optoelectronic Co.,Ltd. All rights reserved.
//

#define udp_MulitBoardCast_Host @"224.0.0.1"  /*1.1莫名其妙就是不行*/
#define udp_MulitBoardCast_Port 12333

#import "UdpSingleton.h"

@implementation UdpSingleton

#pragma mark-init
+(UdpSingleton*) shareInstance
{
    static UdpSingleton *shareInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        shareInstance = [[self alloc]init];
    });
    return shareInstance;
}

-(id)init{
    self = [super init];
    if (self) {
        bufferData = [[NSMutableData alloc]init];
    }
    return self;
}


#pragma mark-设置UDP
-(void) openUdpServerWithDefault
{
    [self openUdpServerWithHost:udp_MulitBoardCast_Host withPort:udp_MulitBoardCast_Port];
}

-(void) openUdpServerWithHost:(NSString*)host withPort:(UInt16) port
{
    self.udpHost = host;
    self.udpPort = port;
    if (self.udpHost == nil) {
        self.udpHost = udp_MulitBoardCast_Host;
    }
    if (self.udpPort == 0) {
        self.udpPort = udp_MulitBoardCast_Port;
    }
    
    //初始化UDP，只接收IPV4发报
    AsyncUdpSocket *tempSocket = [[AsyncUdpSocket alloc]initIPv4];
    self.udpSocket = tempSocket;
    [self.udpSocket setDelegate:self];
    
    //绑定端口
    NSError *error = nil;
    if ([self.udpSocket bindToPort:self.udpPort error:&error ])
    {
        NSLog(@"建立连接%@",error);
    }
    
    //允许发送组播
    if ([self.udpSocket enableBroadcast:YES error:&error]) {
        NSLog(@"允许广播%@",error);
    }
    
    //加入广播组
    if ([self.udpSocket joinMulticastGroup:self.udpHost error:&error]) {
        NSLog(@"加入广播%@",error);
    }
    
    //获取MTU  这里写一下：因为路由器的问题导致了包越大，越慢
    [self.udpSocket setMaxReceiveBufferSize:63000];
    NSLog(@"MTU:%d",[self.udpSocket maxReceiveBufferSize]);
    

    
    
    //启动接收线程
    [self.udpSocket receiveWithTimeout:-1 tag:0];
}


// 认UDP收图片
-(BOOL)onUdpSocket:(AsyncUdpSocket *)sock didReceiveData:(NSData *)data withTag:(long)tag fromHost:(NSString *)host port:(UInt16)port
{

    

//    接收字符串
//    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//    if (msg)
//    {
//        NSLog(@"%@",msg);
//    }
    
    //收到字节数
    NSLog(@"收到udp包：字节数：%d",(int)data.length);
    
    //相界面传递数据
    [self.adelegate displaySendScene:data];
    
    //持续接收
    [self.udpSocket receiveWithTimeout:-1 tag:0];
    return YES;
}

@end
